require 'Common/define'
require 'Logic/Config'
require 'Common/functions'

UICharactorReborn = {};
HelperFunc.SetUIEnv(UICharactorReborn)
local this = UICharactorReborn;

this.gameObject = nil;
this.transform = nil;
this.LuaBehaviour = nil;

this.hasInit = false;

this.currentData = nil;
this.charactorExpConfig = nil;
this.heroRankConfig = nil;
this.heroConfig = nil;
this.itemConfig = nil;
this.equipConfig = nil;

this.txtTile = nil;
this.txtRewardTile = nil;
this.btnClose = nil;
this.objHeroPos = nil;
---@type FairyGUI.GList
this.gridItemParent = nil;
this.btnReborn = nil;
this.txtCost = nil;
this.imgCost = nil;
this.txtReborn = nil;

this.headRectItem = nil;
this.items = {};

this.isType = 0;--0英雄重置 1援助技重置
this.typeController = nil;
function UICharactorReborn.Init(data, isSupSkill)
    --todo 应该小写 暂时先大写
    local name, package = getUIName(PanelNames.UICharactorReborn);
    currentData = clone(data);
    if isSupSkill == 1 then
        isType = 1;
    else
        isType = 0;
        if charactorExpConfig == nil then
            charactorExpConfig = G.dataTable["t_characterexp"];
        end
        if heroRankConfig == nil then
            heroRankConfig = G.dataTable["t_herorank"];
        end
        if heroConfig == nil then
            heroConfig = G.dataTable["t_hero"];
        end
        if itemConfig == nil then
            itemConfig = G.dataTable["t_item"];
        end
        if equipConfig == nil then
            equipConfig = dataTable.getDataTable("t_equip");
        end
    end
    panelMgr:ShowUI(name, package, this.onCreate, Config.useLocalUI);

end
---@param obj FairyGUI.GComponent
function UICharactorReborn.onCreate(obj)
    AddUIPackageDepend(PanelNames.UICharactorReborn, "FUI/HalfBodyAtlas")
    if not hasInit then
        hasInit = true;
        gridItemParent = obj:GetChild("ItemSv");

        txtTile = obj:GetChild("Bg_Title")
        txtRewardTile = obj:GetChild("title_Text")
        btnClose = obj:GetChild("CloseBtn")
        --objHeroPos = obj:GetChild("card");
        headRectItem = obj:GetChild("card")
        btnReborn = obj:GetChild("btn_start")
        txtCost = obj:GetChild("CostNumText")
        imgCost = obj:GetChild("consume")
        --援助技重置
        supSkillItem = obj:GetChild("supSkillItem")
        skillLv = obj:GetChild("SkillLv")
        skillTips = obj:GetChild("SkillTips")
        costNumText = obj:GetChild("CostNumText")

        typeController = obj:GetController("c1");
        this.addEvent();
    end
    txtRewardTile.text = getLanguage("Sys_HeroResetReturn");
    if isType == 1 then
        typeController.selectedIndex = 1;
        this.refreshSupSkill();
    else
        typeController.selectedIndex = 0;
        this.refresh();
    end
end

function UICharactorReborn.addEvent()
    btnClose.onClick:Add(this.onClickClose)
    btnReborn.onClick:Add(this.onClickReborn)
end

function UICharactorReborn.removeEvent()
    btnClose.onClick:Clear()
    btnReborn.onClick:Clear()
end

function UICharactorReborn.LocalListenEvent()
    ListenEvent(Config.EventType.Fresh_HeroReborn, this.resetData);
    ListenEvent(Config.EventType.Fresh_AssistantSkillReset, this.resetData);

end

function UICharactorReborn.LocalCloseEvent()
    CloseEvent(Config.EventType.Fresh_HeroReborn, this.resetData);
    CloseEvent(Config.EventType.Fresh_AssistantSkillReset, this.resetData);

end

function UICharactorReborn.OnDestroy()
    this.removeEvent();
end

function UICharactorReborn.OnEnable()
    this.LocalListenEvent();
end

function UICharactorReborn.OnDisable()
    this.LocalCloseEvent();
end

function UICharactorReborn.resetData()
    if currentData ~= nil then
        if isType == 0 then
            currentData = logicMgr.HeroManager.getHeroDatabyPartnerId(currentData.partnerId);
            if currentData == nil or currentData.level <= 1 then
                UISysTips.AddMsg("重生成功");
                this.onClickClose();
            else
                this.refresh();
            end
        else
            UISysTips.AddMsg(getLanguage("WishFountain_Reset_Btn")..getLanguage("ErrorCode_0"));
            this.onClickClose();

        end
    end
end

function UICharactorReborn.refreshSupSkill()
    --local skillGroup = logicMgr.SkillManager.getSupSkillConfig();
    local id = currentData.id;
    local cfg = G.dataTable["t_assistantskill"][tostring(id)];
    local cfgShow = G.dataTable["t_skillshow"][tostring(id)];
    supSkillItem:GetChild("Mask"):GetChild("Icon").url =  "ui://SkillAtlas/" .. cfgShow.f_SkillIcon;
    supSkillItem:GetChild("number").text = cfg.f_Level;
    skillLv.text = cfg.f_Level;
    skillTips.text = cfgShow.f_Desc;
    costNumText.text = G.dataTable["t_global"]["239"].f_int_value;
    gridItemParent:RemoveChildrenToPool()
    local item = gridItemParent:AddItemFromPool()
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.Item);
    local costData =decodeJsonStrToTabel(cfg.f_ResetReturn);
    local data = logicMgr.ItemManager.getItemConstDatabyModelId(costData[1][1]);
    data["num"] = costData[1][2];
    ctrlItem.initData(item, data);
end

function UICharactorReborn.refresh()
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.HeadRectBItem);
    if ctrlItem ~= nil then
        currentData["notShowNum"] = true;
        ctrlItem.initData(headRectItem, currentData, LuaBehaviour);
    end

    local costCg = G.dataTable["t_global"]["44"];
    txtCost.visible = costCg ~= nil;
    imgCost.visible = costCg ~= nil;
    if costCg ~= nil then
        txtCost.text = costCg.f_int_value;
        local itemCg = itemConfig[tostring(CurrencyEnum.GOLD)];
        imgCost.url = "ui://ItemAtlas/" .. itemCg.f_Icon
    end

    local dataItems = {};
    dataItems[CurrencyEnum.HeroExp] = 0;
    for i = 1, currentData.level - 1 do
        dataItems[CurrencyEnum.HeroExp] = dataItems[CurrencyEnum.HeroExp] + charactorExpConfig[MakeTopLevelId(i)]["f_HeroExp"];
        local costArray = decodeJsonStrToTabel(charactorExpConfig[MakeTopLevelId(i)]["f_HeroCost"]);
        for k = 1, #costArray do
            local costItem = costArray[k];
            if dataItems[costItem[1]] ~= nil then
                dataItems[costItem[1]] = dataItems[costItem[1]] + costItem[2];
            else
                dataItems[costItem[1]] = costItem[2];
            end
        end
    end
    local curHeroConfig = heroConfig[tostring(currentData["partnerModelId"])];

    local starId = curHeroConfig.f_HeroInitialStar + curHeroConfig.f_HeroID * 10;

    local endStarId = currentData["star"] + currentData["partnerModelId"] * 10;
    local herorankConfig = heroRankConfig[tostring(starId)];
    while herorankConfig ~= nil do
        if herorankConfig.f_HeroStarNext == nil or herorankConfig.f_HeroStarNext == 0 or herorankConfig.f_HeroRankID >= endStarId then
            break ;
        end
        if herorankConfig.f_RankChipCost ~= nil and #herorankConfig.f_RankChipCost > 0 then
            local chipArr = decodeJsonStrToTabel(herorankConfig.f_RankChipCost);
            local chipId = chipArr[1];
            if dataItems[chipId] == nil then
                dataItems[chipId] = 0;
            end

            dataItems[chipId] = dataItems[chipId] + chipArr[2];
            local costArray = decodeJsonStrToTabel(herorankConfig.f_RankItemCost);
            if costArray ~= nil then
                for i = 1, #costArray do
                    local costItem = costArray[i];
                    if dataItems[costItem[1]] ~= nil then
                        dataItems[costItem[1]] = dataItems[costItem[1]] + costItem[2];
                    else
                        dataItems[costItem[1]] = costItem[2];
                    end
                end
            end
        end
        herorankConfig = heroRankConfig[tostring(herorankConfig.f_HeroStarNext)];
    end
    gridItemParent:RemoveChildrenToPool()
    for k, v in pairs(dataItems) do
        local itemConfig_2 = itemConfig[tostring(k)];
        if itemConfig_2 ~= nil and v > 0 then
            local item = gridItemParent:AddItemFromPool()
            local ctrlItem = CtrlManager.GetCtrl(PanelNames.Item);
            if ctrlItem ~= nil and item ~= nil then
                local data = {};
                data["icon"] = itemConfig_2.f_Icon;
                data["num"] = v;
                data["name"] = getLanguage(itemConfig_2.f_ItemName);
                data["quality"] = itemConfig_2.f_Quality;
                data["itemType"] = itemConfig_2.f_BagType;
                data["desc"] = getLanguage(itemConfig_2.f_Desc);
                data["scriptId"] = itemConfig_2.f_ScriptId;
                data.itemModelId = itemConfig_2.f_itemModelId
                ctrlItem.initData(item, data, LuaBehaviour);
            end
        end
    end
end

function UICharactorReborn.creteItem(id, num, status)
    --status ==1时代表装备,0代表道具
    local config = status and equipConfig[tostring(id)] or itemConfig[tostring(id)];
    if config == nil then
        return nil;
    end
    local item = {};
    item["id"] = id;
    item["state"] = status;
    item["num"] = num;
    if status then
        item["icon"] = config["f_EquipIcon"];
        item["quality"] = config["f_EquipQuality"];
        item["level"] = config["f_EquipLv"];
    else
        item["icon"] = config["f_Icon"];
        item["quality"] = config["f_Quality"];
    end
    return item;
end

function UICharactorReborn.onClickClose()
    closeUI(PanelNames.UICharactorReborn);
end

function UICharactorReborn.onClickReborn()
    if isType == 0 then
        local costCg = G.dataTable["t_global"]["44"];
        if costCg ~= nil and logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD) < costCg.f_int_value then
            UISysTips.AddMsg("道具不足，无法重生");
            AudioManager.Play(2010)
            return ;
        end
        partnerHandler.sendPartnerReset(this.currentData.partnerId);
    else
        local costCg = G.dataTable["t_global"]["239"]
        if costCg ~= nil and logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD) < costCg.f_int_value then
            UISysTips.AddMsg("道具不足，无法重生");
            AudioManager.Play(2010)
            return ;
        end
        skillHandler.SendReqResetSkill(this.currentData.id)
    end
end
return UICharactorReborn;
